package com.freemarker;

import java.io.IOException;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;

/**
 * 
 * Freemarker 模板配置类，封装了配置细节，单例。并且提供template的获取方法。
 * 
 * @author  tom.fan
 * @version  [版本号, Nov 18, 2011]
 * @see  [相关类/方法]
 * @since  [产品/模块版本]
 */
public class FreemarkerConfiguration {
    
    private static FreemarkerConfiguration instance = new FreemarkerConfiguration();
    
    private final Map<String, Configuration> configMap = new HashMap<String, Configuration>();
    
    public static FreemarkerConfiguration getInstance() {
        return instance;
    }
    
    /**
     * 根据classpath路径得到配置。
     * @param pathPrefix src中的路径，绝对路径
     * @return
     */
    public synchronized Configuration getConfiguration (String pathPrefix) {
        Configuration conf = this.configMap.get(pathPrefix);
        if (conf == null) {
            conf = new Configuration();
            conf.setClassForTemplateLoading(FreemarkerConfiguration.class, pathPrefix);
            conf.setEncoding(Locale.getDefault(), "UTF-8");
            conf.setObjectWrapper(new DefaultObjectWrapper());
            this.configMap.put(pathPrefix, conf);
        }
        return conf;
    }
    
    /**
     * 得到某classpath路径下的模板类
     * @param pathPrefix
     * @param tempName
     * @return
     * @throws IOException
     */
    public Template getTemplate(String pathPrefix, String tempName) throws IOException {
        Template temp = null;
        Configuration conf = this.getConfiguration(pathPrefix);
        if (conf != null) {
            temp = conf.getTemplate(tempName);
        }
        return temp;
    }
    
}
